/*
 * Sylvain BERTRAND <digital.ragnarok@gmail.com>
 * code protected by GNU GPL v3
 */
#include <X11/Xlib.h>
#include <glib.h>
#include <libxml/xinclude.h>
#include "../../toolkit/keyboard.h"
#include "../../toolkit/xml.h"
#include "../misc.h"
#include "../geom.h"
#include "../frame.h"
#include "../actions.h"
#include "../window.h"
#include "../stacking.h"
#include "../client.h"
struct options {
	gint layer;
	gboolean toggle;
};

static gpointer setup_func_top(xmlNodePtr node)
{
	struct options *o = g_slice_new0(struct options);
	(void)node;
	o->layer = 1;
	o->toggle = TRUE;
	return o;
}

static gpointer setup_func_bottom(xmlNodePtr node)
{
	struct options *o = g_slice_new0(struct options);
	(void)node;
	o->layer = -1;
	o->toggle = TRUE;
	return o;
}

static gpointer setup_func_send(xmlNodePtr node)
{
	xmlNodePtr n;
	struct options *o;
	o = g_slice_new0(struct options);
	if((n = t_xml_find_node(node, "layer"))) {
		gchar *s = t_xml_node_string(n);
		if(!g_ascii_strcasecmp(s, "above") || !g_ascii_strcasecmp(s, "top"))
			o->layer = 1;
		else if(!g_ascii_strcasecmp(s, "below") || !g_ascii_strcasecmp(s, "bottom"))
			o->layer = -1;
		else if(!g_ascii_strcasecmp(s, "normal") || !g_ascii_strcasecmp(s, "middle"))
			o->layer = 0;
		g_free(s);
	}
	return o;
}

static void free_func(gpointer o)
{
	g_slice_free(struct options, o);
}

static gboolean run_func(struct wm_actions_data *data, gpointer options)
{
	struct options *o = options;
	if(data->client) {
		struct wm_client *c = data->client;
		actions_client_move(data, TRUE);
		if(o->layer < 0) {
			if(o->toggle || !c->below)
				client_set_layer(c, c->below ? 0 : -1);
		} else if(o->layer > 0) {
			if(o->toggle || !c->above)
				client_set_layer(c, c->above ? 0 : 1);
		} else if(c->above || c->below)
			client_set_layer(c, 0);
		actions_client_move(data, FALSE);
	}
	return FALSE;
}

static gpointer setup_sendtop_func(xmlNodePtr node)
{
	struct options *o = g_slice_new0(struct options);
	(void)node;
	o->layer = 1;
	o->toggle = FALSE;
	return o;
}

static gpointer setup_sendbottom_func(xmlNodePtr node)
{
	struct options *o = g_slice_new0(struct options);
	(void)node;
	o->layer = -1;
	o->toggle = FALSE;
	return o;
}

static gpointer setup_sendnormal_func(xmlNodePtr node)
{
	struct options *o = g_slice_new0(struct options);
	(void)node;
	o->layer = 0;
	o->toggle = FALSE;
	return o;
}

void action_layer_startup(void)
{
	actions_register("ToggleAlwaysOnTop", setup_func_top, free_func, run_func);
	actions_register("ToggleAlwaysOnBottom", setup_func_bottom, free_func, run_func);
	actions_register("SendToLayer", setup_func_send, free_func, run_func);
	actions_register("SendToTopLayer", setup_sendtop_func, free_func, run_func);
	actions_register("SendToBottomLayer", setup_sendbottom_func, free_func, run_func);
	actions_register("SendToNormalLayer", setup_sendnormal_func, free_func, run_func);
}
